package com.cndongtai.controller.config;

import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cndongtai.constant.RspCodeConstant;
import com.cndongtai.constant.UserConstant;
import com.cndongtai.controller.BaseController;
import com.cndongtai.po.Dtu;
import com.cndongtai.po.Light;
import com.cndongtai.po.LightConfig;
import com.cndongtai.po.LightConfigTemplate;
import com.cndongtai.po.User;
import com.cndongtai.service.config.LightConfigService;
import com.cndongtai.service.light.DtuService;
import com.cndongtai.service.light.LightService;
import com.cndongtai.service.net.NetService;
import com.cndongtai.util.ValidateUtil;
import com.cndongtai.vo.LightConfigTemplateBean;

@Controller
public class ConfigController extends BaseController {
	
	@Resource(name="lightConfigService")
	private LightConfigService lightConfigService;
	
	@Resource(name="lightService")
	private LightService lightService;
	
	@Resource(name="netService")
	private NetService netService;
	
	@Resource(name="dtuService")
	private DtuService dtuService;
	
	@RequestMapping("/showConfig")
	public String showConfig() {
		User user = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		if("admin".equals(user.getUsername())) {
			List<LightConfigTemplateBean> templateList = lightConfigService.queryConfigTemplateList(null);
			request.setAttribute("templateList", templateList);
		}else {
			List<LightConfigTemplateBean> templateList = lightConfigService.queryConfigTemplateList(user.getUserId());
			request.setAttribute("templateList", templateList);
		}
		
		String jsonTree = lightService.getLightJsonTree();
		request.setAttribute("jsonTree", jsonTree);
		
		return "config/configMgr";
	}
	
	@RequestMapping("/queryConfigTemplateList")
	@ResponseBody
	public void queryConfigTemplateList() {
		User user = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		List<LightConfigTemplateBean> templateList = null;
		if("admin".equals(user.getUsername())) {
			templateList = lightConfigService.queryConfigTemplateList(null);
		}else {
			templateList = lightConfigService.queryConfigTemplateList(user.getUserId());
		}
		
		JSONObject result = new JSONObject();
		StringBuffer sb = new StringBuffer();
		if(templateList==null || templateList.size()==0) {
			result.put("success", "-1");
			result.put("templateHtml", sb.toString());
			this.writeData(result);
			return;
		}
		for(LightConfigTemplateBean bean : templateList) {
			sb.append("<option value='").append(bean.getTemplateId()).append("'>").append(bean.getTemplateName()).append("</option>");
		}
		
		result.put("success", "0");
		result.put("templateHtml", sb.toString());
		this.writeData(result);
	}
	
	@RequestMapping("/deleteConfigTemplate")
	@ResponseBody
	public void deleteConfigTemplate() {
		JSONObject result = new JSONObject();
		String templateId = this.getValue("templateId");
		if(!lightConfigService.delLightConfigTemplate(Long.valueOf(templateId))) {
			result.put("success", "1");
			result.put("msg", getMessage("config.msg.delete.fail",null));
			this.writeData(result);
			return;
		}
		
		result.put("success", "0");
		result.put("msg", getMessage("config.msg.delete.success",null));
		this.writeData(result);
	}
	
	@RequestMapping("/gotoAddConfitTemplate")
	public String gotoAddConfitTemplate() {
		return "config/addConfigTemplate";
	}
	
	@RequestMapping("/addConfigTemplate")
	@ResponseBody
	public void addConfigTemplate() {
		JSONObject result = new JSONObject();
		
		String templateName = this.getValue("templateName");
		String controlModelOn = this.getValue("controlModelOn");
		String controlModelDown = this.getValue("controlModelDown");
		String turnonVol = this.getValue("turnonVol");
		String turnonTime = this.getValue("turnonTime");
		String shutdownTime = this.getValue("shutdownTime");
		String workModel = this.getValue("workModel");
		String topVol = this.getValue("topVol");
		String lowVol = this.getValue("lowVol");
		String exitVol = this.getValue("exitVol");
		String lowStartVol = this.getValue("lowStartVol");
		String lowEndVol = this.getValue("lowEndVol");
		String maxWorkCurrent = this.getValue("maxWorkCurrent");
		String time1 = this.getValue("time1");
		String workCurrent1 = this.getValue("workCurrent1");
		String time2 = this.getValue("time2");
		String workCurrent2 = this.getValue("workCurrent2");
		String time3 = this.getValue("time3");
		String workCurrent3 = this.getValue("workCurrent3");
		String time4 = this.getValue("time4");
		String workCurrent4 = this.getValue("workCurrent4");
		
		User user = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		
		LightConfigTemplate configTemplate = new LightConfigTemplate();
		configTemplate.setCreateBy(user.getUserId());
		configTemplate.setTemplateName(templateName);
		configTemplate.setControlModel(controlModelOn + controlModelDown);
		if("1".equals(controlModelOn)) {
			configTemplate.setTurnonVol((int)Double.parseDouble(turnonVol)*10);
		}else if("2".equals(controlModelOn)) {
			configTemplate.setTurnonTime(turnonTime);
		}
		
		if("2".equals(controlModelDown)) {
			configTemplate.setShutdownTime(shutdownTime);
		}
		
		if("2".equals(controlModelOn) && "1".equals(controlModelDown)) {
			configTemplate.setTurnonVol((int)Double.parseDouble(turnonVol)*10 + 10);
		}
		
		configTemplate.setWorkModel(workModel);
		configTemplate.setTopVol((int)(Double.parseDouble(topVol)*10));
		configTemplate.setLowVol((int)(Double.parseDouble(lowVol)*10));
		configTemplate.setExitVol((int)(Double.parseDouble(exitVol)*10));
		configTemplate.setLowStartVol((int)(Double.parseDouble(lowStartVol)*10));
		configTemplate.setLowEndVol((int)(Double.parseDouble(lowEndVol)*10));
		configTemplate.setMaxWorkCurrent(Integer.parseInt(maxWorkCurrent));
		configTemplate.setTime1(Integer.parseInt(time1));
		configTemplate.setWorkCurrent1(Integer.parseInt(workCurrent1));
		configTemplate.setTime2(Integer.parseInt(time2));
		configTemplate.setWorkCurrent2(Integer.parseInt(workCurrent2));
		configTemplate.setTime3(Integer.parseInt(time3));
		configTemplate.setWorkCurrent3(Integer.parseInt(workCurrent3));
		configTemplate.setTime4(Integer.parseInt(time4));
		configTemplate.setWorkCurrent4(Integer.parseInt(workCurrent4));
		
		lightConfigService.addConfigTemplate(configTemplate);

		result.put("success", 0);
		result.put("msg", getMessage("config.msg.add.success",null));
		this.writeData(result);
	}
	
	@RequestMapping("/configRtu")
	@ResponseBody
	public void configRtu() {
		String lightIdStr = this.getValue("lightId");
		String templateIdStr = this.getValue("templateId");
		
		JSONObject result = new JSONObject();
		if(ValidateUtil.empty(lightIdStr)) {
			result.put("success", "-1");
			result.put("msg", getMessage("config.msg.device.notexist",null));
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(templateIdStr)) {
			result.put("success", "-1");
			result.put("msg", getMessage("config.msg.template.notexist",null));
			this.writeData(result);
			return;
		}
		
		Light light = lightService.queryLightById(lightIdStr);
		if(light==null) {
			result.put("success", "-1");
			result.put("msg", getMessage("config.msg.device.notexist",null));
			this.writeData(result);
			return;
		}
		
		Dtu dtu = dtuService.queryDtuById(light.getDtuId()+"");
		if(dtu==null) {
			result.put("success", "-1");
			result.put("msg", getMessage("config.msg.device.notexist",null));
			this.writeData(result);
			return;
		}
		
		
		LightConfigTemplate template = lightConfigService.queryConfigTemplateById(Integer.parseInt(templateIdStr));
		if(template==null) {
			result.put("success", "-1");
			result.put("msg", getMessage("config.msg.template.notexist",null));
			this.writeData(result);
			return;
		}
		
		String resultCode = netService.rtuConfig(dtu.getPanId(), light.getLightNum(),template);
		
		if(RspCodeConstant.SUCCESS.equals(resultCode)) {
			LightConfig config = new LightConfig();
			config.setLightId(light.getLightId());
			config.setControlModel(template.getControlModel());
			config.setTurnonVol(template.getTurnonVol());
			config.setTurnonTime(template.getTurnonTime());
			config.setShutdownTime(template.getShutdownTime());
			config.setWorkModel(template.getWorkModel());
			config.setTopVol(template.getTopVol());
			config.setLowVol(template.getLowVol());
			config.setExitVol(template.getExitVol());
			config.setLowStartVol(template.getLowStartVol());
			config.setLowEndVol(template.getLowEndVol());
			config.setMaxWorkCurrent(template.getMaxWorkCurrent());
			config.setTime1(template.getTime1());
			config.setWorkCurrent1(template.getWorkCurrent1());
			config.setTime2(template.getTime2());
			config.setWorkCurrent2(template.getWorkCurrent2());
			config.setTime3(template.getTime3());
			config.setWorkCurrent3(template.getWorkCurrent3());
			config.setTime4(template.getTime4());
			config.setWorkCurrent4(template.getWorkCurrent4());
			
			lightConfigService.addLightConfig(config);
			
			result.put("success", "0");
			result.put("msg", getMessage("config.msg.success",null));
		}else {
			result.put("success", "-1");
			String msg = getMessage("config.msg.fail.error"+resultCode,null);
			if(msg==null || "".equals(msg)) {
				msg = getMessage("config.msg.fail",null);
			}
			result.put("msg", msg);
		}
		
		this.writeData(result);
		return;
	}
	
	@RequestMapping("/templateDetail")
	@ResponseBody
	public void templateDetail() {
		JSONObject result = new JSONObject();
		String templateIdStr = this.getValue("templateId");
		if(ValidateUtil.empty(templateIdStr)) {
			result.put("success", 1);
			result.put("msg", getMessage("data.error",null));
			this.writeData(result);
			return;
		}
		
		LightConfigTemplate template = lightConfigService.queryConfigTemplateById(Integer.valueOf(templateIdStr));
		
		if(template!=null) {
			LightConfigTemplateBean templateBean = convertConfigTemplate2ConfigTemplateBean(template);
			
			result.put("success", 0);
			result.put("templateBean", templateBean);
		}else {
			result.put("success", 1);
			result.put("msg", getMessage("data.error",null));
		}
		this.writeData(result);
	}
	
	private LightConfigTemplateBean convertConfigTemplate2ConfigTemplateBean(LightConfigTemplate template) {
		LightConfigTemplateBean templateBean = new LightConfigTemplateBean();
		
		templateBean.setTemplateId(template.getTemplateId());
		templateBean.setTemplateName(template.getTemplateName());
		templateBean.setControlModel(template.getControlModel());
		templateBean.setControlModelOn(template.getControlModel().substring(0,1));
		templateBean.setControlModelDown(template.getControlModel().substring(1));
		templateBean.setTurnonVol(template.getTurnonVol()!=null?template.getTurnonVol()/10.0 + "" : "");
		templateBean.setTurnonTime(template.getTurnonTime());
		templateBean.setShutdownTime(template.getShutdownTime());
		templateBean.setWorkModel(template.getWorkModel());
		templateBean.setTopVol(template.getTopVol()/10.0 + "");
		templateBean.setLowVol(template.getLowVol()/10.0 + "");
		templateBean.setExitVol(template.getExitVol()/10.0 + "");
		templateBean.setLowStartVol(template.getLowStartVol()/10.0 + "");
		templateBean.setLowEndVol(template.getLowEndVol()/10.0 + "");
		templateBean.setMaxWorkCurrent(template.getMaxWorkCurrent());
		templateBean.setTime1(template.getTime1());
		templateBean.setWorkCurrent1(template.getWorkCurrent1());
		templateBean.setTime2(template.getTime2());
		templateBean.setWorkCurrent2(template.getWorkCurrent2());
		templateBean.setTime3(template.getTime3());
		templateBean.setWorkCurrent3(template.getWorkCurrent3());
		templateBean.setTime4(template.getTime4());
		templateBean.setWorkCurrent4(template.getWorkCurrent4());
		
		return templateBean;
	}
	
	@RequestMapping("/gotoConfigLights")
	public String gotoConfigLights() {
		String templateId = this.getValue("templateId");
		if(ValidateUtil.empty(templateId)) {
			return "redirect:showConfig.do";
		}
		
		String jsonTree = lightService.getLightJsonTree();
		request.setAttribute("jsonTree", jsonTree);
		request.setAttribute("templateId", templateId);
		
		return "config/configLights";
	}
	
	@RequestMapping("/configLights")
	@ResponseBody
	public void configLights() {
		JSONObject result =  new JSONObject();
		String templateId = this.getValue("templateId");
		String lightIds = this.getValue("lightIds");
		if(ValidateUtil.empty(templateId)) {
			result.put("success", "-1");
			result.put("msg", getMessage("config.msg.template.notexist",null));
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(lightIds)) {
			result.put("success", "-1");
			result.put("msg", getMessage("config.msg.selectdevice",null));
			this.writeData(result);
			return;
		}
		
		String[] lightIdArr = lightIds.split(",");
		if(lightIdArr.length==0) {
			result.put("success", "-1");
			result.put("msg", getMessage("config.msg.selectdevice",null));
			this.writeData(result);
			return;
		}
		
		LightConfigTemplate template = lightConfigService.queryConfigTemplateById(Integer.parseInt(templateId));
		if(template==null) {
			result.put("success", "-1");
			result.put("msg", getMessage("config.msg.template.notexist",null));
			this.writeData(result);
			return;
		}
		
		StringBuffer resultMsg = new StringBuffer();
		for(String lightIdStr : lightIdArr) {
			Light light = lightService.queryLightById(lightIdStr);
			if(light==null) {
				continue;
			}
			
			Dtu dtu = dtuService.queryDtuById(light.getDtuId()+"");
			if(dtu==null) {
				continue;
			}
			
			for(int i=1;i<=3;i++) {
				String resultCode = netService.rtuConfig(dtu.getPanId(), light.getLightNum(),template);
				if(RspCodeConstant.SUCCESS.equals(resultCode)) {
					LightConfig config = new LightConfig();
					config.setLightId(light.getLightId());
					config.setControlModel(template.getControlModel());
					config.setTurnonVol(template.getTurnonVol());
					config.setTurnonTime(template.getTurnonTime());
					config.setShutdownTime(template.getShutdownTime());
					config.setWorkModel(template.getWorkModel());
					config.setTopVol(template.getTopVol());
					config.setLowVol(template.getLowVol());
					config.setExitVol(template.getExitVol());
					config.setLowStartVol(template.getLowStartVol());
					config.setLowEndVol(template.getLowEndVol());
					config.setMaxWorkCurrent(template.getMaxWorkCurrent());
					config.setTime1(template.getTime1());
					config.setWorkCurrent1(template.getWorkCurrent1());
					config.setTime2(template.getTime2());
					config.setWorkCurrent2(template.getWorkCurrent2());
					config.setTime3(template.getTime3());
					config.setWorkCurrent3(template.getWorkCurrent3());
					config.setTime4(template.getTime4());
					config.setWorkCurrent4(template.getWorkCurrent4());
					
					lightConfigService.addLightConfig(config);
					resultMsg.append(getMessage("config.msg.device",null)).append(light.getLightNum()).append(getMessage("config.msg.success",null)+"！").append("\n");
					break;
				}else {
					if(i==3) {
						String msg = getMessage("config.msg.fail.error"+resultCode,null);
						if(msg==null || "".equals(msg)) {
							msg = getMessage("config.msg.fail",null);
						}
						
						resultMsg.append(getMessage("config.msg.device",null)).append(light.getLightNum()).append(msg+"！").append("\n");
					}else {
						try {
							Thread.sleep(1000*5);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
		
		result.put("success", "0");
		result.put("msg", resultMsg.toString());
		this.writeData(result);
	}

}
